/*
 * Copyright (C) 2018 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.materialme;

import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.View;

import java.util.ArrayList;
import java.util.Collections;

/***
 * Main Activity for the Material Me app, a mock sports news application
 * with poor design choices.
 */
public class MainActivity extends AppCompatActivity {

  // Member variables.
  private RecyclerView mRecyclerView;
  private ArrayList<Sport> mSportsData;
  private SportsAdapter mAdapter;
  private ArrayList<CharSequence> mTitles;

  private final static String TITLES_KEY = "sportTitles";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Initialize the RecyclerView.
    mRecyclerView = findViewById(R.id.recyclerView);

    int gridColumnCount =
        getResources().getInteger(R.integer.grid_column_count);
    // Set the Layout Manager.
    mRecyclerView.setLayoutManager(new GridLayoutManager(this,
        gridColumnCount));

    // Initialize the ArrayList that will contain the data.
    mSportsData = new ArrayList<>();

    // Initialize the adapter and set it to the RecyclerView.
    Log.d("MainActivity", "set adapter.");
    mAdapter = new SportsAdapter(this, mSportsData);
    mRecyclerView.setAdapter(mAdapter);

    Log.d("MainActivity", "initial data.");
    // Get the data.
    if (savedInstanceState != null) {
      mTitles = savedInstanceState.getCharSequenceArrayList(TITLES_KEY);
    }
    initializeData();

    ItemTouchHelper touchHelper = setTouchHelper(gridColumnCount);
    touchHelper.attachToRecyclerView(mRecyclerView);
  }

  private ItemTouchHelper setTouchHelper(int column) {
    int swipeDirs = column > 1 ? 0 :
        ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
    return new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(
        ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT,
        swipeDirs) {
      @Override
      public boolean onMove(RecyclerView recyclerView,
          RecyclerView.ViewHolder viewHolder,
          RecyclerView.ViewHolder target) {
        int from = viewHolder.getAdapterPosition();
        int to = target.getAdapterPosition();
        Collections.swap(mSportsData, from, to);
        mAdapter.notifyItemMoved(from, to);
        return true;
      }

      @Override
      public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        int p = viewHolder.getAdapterPosition();
        mSportsData.remove(p);
        mAdapter.notifyItemRemoved(p);
      }
    });
  }

  /**
   * Initialize the sports data from resources.
   */
  private void initializeData() {
    // Get the resources from the XML file.
    String[] sportsTitle = getResources().getStringArray(R.array.sports_titles);
    String[] sportsInfo = getResources().getStringArray(R.array.sports_info);
    TypedArray sportsImage =
        getResources().obtainTypedArray(R.array.sports_images);

    // Clear the existing data (to avoid duplication).
    mSportsData.clear();

    // Create the ArrayList of Sports objects with titles and
    // information about each sport.
    if (mTitles != null) {
      // 根据保留状态顺序生成新的列表
      for (CharSequence title : mTitles) {
        // 这里可以试用二分查找
        for (int i = 0; i < sportsTitle.length; i++) {
          // java字符串相等比较
          if (title.equals(sportsTitle[i])) {
            mSportsData.add(new Sport(sportsTitle[i],
                sportsInfo[i],
                sportsImage.getResourceId(i, 0)));
            break;
          }
        }
      }
    } else {
      for (int i = 0; i < sportsTitle.length; i++) {
        mSportsData.add(new Sport(sportsTitle[i],
            sportsInfo[i],
            sportsImage.getResourceId(i, 0)));
      }
    }

    // recycle resource
    sportsImage.recycle();

    // Notify the adapter of the change.
    mAdapter.notifyDataSetChanged();
  }

  public void resetSports(View view) {
    mTitles = null;
    this.initializeData();
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    ArrayList<CharSequence> titles = new ArrayList<>();
    for (Sport s : mSportsData) {
      titles.add(s.getTitle());
    }
    outState.putCharSequenceArrayList(TITLES_KEY, titles);
    super.onSaveInstanceState(outState);
  }
}
